/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.serviportales.serviquality.managers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.serviportales.serviquality.dao.NodoDAO;
import com.serviportales.serviquality.exception.ServiqualityException;
import com.serviportales.serviquality.model.Nodo;

@Service
@Transactional(rollbackFor = { ServiqualityException.class })
public class MgrNodos {


	@Autowired
	private NodoDAO nodoDAO;
	@Autowired
	private MessageSource messageSource;

	public void grabarNodo(Nodo nodo) throws ServiqualityException {
		try {
			Nodo nodoFilter = nodoDAO.selectByID(nodo.getNodoPK());
			if (nodoFilter != null) {
				nodoFilter.setDescripcion(nodo.getDescripcion());
				nodoFilter.setEstadoRegistro(nodo.getEstadoRegistro());
				nodoFilter.setNombre(nodo.getNombre());
				nodoDAO.update(nodoFilter);
			} else {
				nodoDAO.insert(nodo);
			}
		} catch (Exception exception) {
			throw new ServiqualityException(messageSource.getMessage(ServiqualityException.GRABAR_ERROR, new String[] { exception.getMessage() }, LocaleContextHolder.getLocale()), exception);
		}
	}

	public List<Nodo> buscarNodo(Nodo nodo) throws ServiqualityException {
		try {
			return nodoDAO.select(nodo);
		} catch (Exception exception) {
			throw new ServiqualityException(messageSource.getMessage(ServiqualityException.BUSCAR_ERROR, new String[] { exception.getMessage() }, LocaleContextHolder.getLocale()), exception);
		}
	}

	public List<Nodo> buscarNodo(Nodo nodo, int maxResult) throws ServiqualityException {
		try {
			return nodoDAO.select(nodo, 0, maxResult);
		} catch (Exception exception) {
			throw new ServiqualityException(messageSource.getMessage(ServiqualityException.BUSCAR_ERROR, new String[] { exception.getMessage() }, LocaleContextHolder.getLocale()), exception);
		}
	}

	public List<Nodo> buscarNodosByNivel(Nodo nodo, int maxResult) throws ServiqualityException {
		try {
			List<Nodo> nodos = nodoDAO.selectByNivel(nodo);
			List<Nodo> result = new ArrayList<Nodo>();
			int cont = 0;
			for (Nodo nodoList : nodos) {
				if (cont++ < maxResult) {
					result.add(nodoList);
				}
			}
			return result;
		} catch (Exception exception) {
			throw new ServiqualityException(messageSource.getMessage(ServiqualityException.BUSCAR_ERROR, new String[] { exception.getMessage() }, LocaleContextHolder.getLocale()), exception);
		}
	}
}
